package org.afs.gescol.core.service.util;

import org.afs.gescol.core.model.data.Teacher;
import org.afs.gescol.core.model.params.Year;
import org.afs.gescol.core.model.references.Level;
import org.afs.gescol.core.model.references.Series;
import org.afs.gescol.core.model.references.Subject;
import org.dozer.CustomConverter;
import org.scub.foundation.framework.base.dto.IdLabelDto;

public class ModelCustomConverter implements CustomConverter {

    @Override
    public Object convert(Object destination, Object source, Class<?> destinationClass, Class<?> sourceClass) {
        if (source == null) {
            return null;
        }
        IdLabelDto dest = null;
        if (destination == null) {
            dest = new IdLabelDto();
        } else {
            dest = (IdLabelDto) destination;
        }
        if (source instanceof Level) {
            final Level level = (Level) source;
            dest.setId(level.getId());
            dest.setLabel(getLabel(level.getShortLabel(), level.getLongLabel()));
        } else if (source instanceof Series) {
            final Series series = (Series) source;
            final boolean ajout = (series.getSeriesLevel() != null && series.getSeriesLevel().getShortLabel() != null
                    && !"".equals(series.getSeriesLevel().getShortLabel()));
            dest.setId(series.getId());
            dest.setLabel(getLabel(series.getShortLabel(), series.getLongLabel())
                + (ajout ? " (" + series.getSeriesLevel().getShortLabel() + ")" : ""));
        } else if (source instanceof Subject) {
            final Subject subject = (Subject) source;
            dest.setId(subject.getId());
            dest.setLabel(subject.getShortLabel() + " - " + subject.getLongLabel());
        } else if (source instanceof Year) {
            final Year year = (Year) source;
            dest.setId(year.getId());
            dest.setLabel(year.getBeginYear() + "-" + year.getEndYear());
        } else if (source instanceof Teacher) {
            final Teacher teacher = (Teacher) source;
            dest.setId(teacher.getId());
            dest.setLabel(teacher.getFirstName() + " " + teacher.getLastName());
        }

        return dest;
    }

    private String getLabel(String shortL, String longL) {
        if (shortL == null) {
            return longL;
        }
        if (longL == null) {
            return shortL;
        }
        if (longL.equals(shortL)) {
            return shortL;
        }
        return shortL + " - " + longL;
    }
}
